package com.bawei.module_live.manager

import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.recyclerview.widget.RecyclerView
import com.bawei.module_live.adapter.VideoPagerAdapter
import com.bawei.module_live.layout.VideoLayoutManager
import com.bawei.module_live.player.ExoPlayerManager
import com.bawei.module_live.version1.VideoEntityItem

class VideoPlayerManager {
    
    companion object {
        private const val TAG = "VideoPlayerManager"
    }
    
    private var currentPosition = -1
    private var recyclerView: RecyclerView? = null
    private var exoPlayerManager: ExoPlayerManager? = null
    private var onVideoPlayListener: ((VideoEntityItem, Int) -> Unit)? = null
    private var onVideoPauseListener: ((VideoEntityItem, Int) -> Unit)? = null
    private val handler = Handler(Looper.getMainLooper())
    private var playRetryCount = 0
    private val MAX_RETRY = 5
    private val RETRY_DELAY = 100L
    
    fun setRecyclerView(rv: RecyclerView, exoPlayerManager: ExoPlayerManager) {
        recyclerView = rv
        this.exoPlayerManager = exoPlayerManager
        setupScrollListener()
    }
    
    fun setOnVideoPlayListener(listener: (VideoEntityItem, Int) -> Unit) {
        onVideoPlayListener = listener
    }
    
    fun setOnVideoPauseListener(listener: (VideoEntityItem, Int) -> Unit) {
        onVideoPauseListener = listener
    }
    
    private fun setupScrollListener() {
        recyclerView?.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    // 滚动停止时，播放当前可见的视频
                    playCurrentVideo()
                } else if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                    // 开始滚动时，暂停当前视频
                    pauseCurrentVideo()
                }
            }
        })
    }
    
    public fun playCurrentVideo() {
        try {
            val layoutManager = recyclerView?.layoutManager
            if (layoutManager is VideoLayoutManager) {
                val centerPosition = layoutManager.getCurrentVisiblePosition()
                Log.d(TAG, "当前中心位置: $centerPosition, 之前位置: $currentPosition")
                if (centerPosition != currentPosition && centerPosition >= 0) {
                    pauseCurrentVideo()
                    currentPosition = centerPosition
                    val adapter = recyclerView?.adapter
                    if (adapter is VideoPagerAdapter) {
                        val video = adapter.getVideoAtPosition(currentPosition)
                        if (video != null) {
                            val viewHolder = recyclerView?.findViewHolderForAdapterPosition(currentPosition)
                            if (viewHolder is VideoPagerAdapter.VideoViewHolder) {
                                playRetryCount = 0 // reset retry count
                                val playerView = viewHolder.getPlayerView()
                                val videoCover = viewHolder.getVideoCover()
                                Log.d(TAG, "准备播放视频: ${video.title} at position: $currentPosition")
                                Log.d(TAG, "视频路径: ${video.videopath}")
                                exoPlayerManager?.setPlayerView(playerView)
                                videoCover.visibility = android.view.View.GONE
                                exoPlayerManager?.playVideo(video, currentPosition)
                                onVideoPlayListener?.invoke(video, currentPosition)
                                Log.d(TAG, "播放视频: ${video.title} at position: $currentPosition")
                            } else {
                                // ViewHolder 还没渲染，延迟重试
                                if (playRetryCount < MAX_RETRY) {
                                    playRetryCount++
                                    handler.postDelayed({ playCurrentVideo() }, RETRY_DELAY)
                                    Log.w(TAG, "未找到 ViewHolder for position: $currentPosition，重试第 $playRetryCount 次")
                                } else {
                                    playRetryCount = 0
                                    Log.e(TAG, "多次重试后仍未找到 ViewHolder for position: $currentPosition")
                                }
                            }
                        } else {
                            Log.w(TAG, "未找到视频数据 for position: $currentPosition")
                        }
                    }
                } else {
                    Log.d(TAG, "位置未变化或无效位置: $centerPosition")
                }
            } else {
                Log.w(TAG, "布局管理器不是 VideoLayoutManager")
            }
        } catch (e: Exception) {
            Log.e(TAG, "playCurrentVideo error: ${e.message}")
            e.printStackTrace()
        }
    }
    
    public fun pauseCurrentVideo() {
        try {
            if (currentPosition >= 0) {
                val adapter = recyclerView?.adapter
                if (adapter is VideoPagerAdapter) {
                    val video = adapter.getVideoAtPosition(currentPosition)
                    if (video != null) {
                        // 暂停视频播放
                        exoPlayerManager?.pausePlayback()
                        // 显示视频封面
                        val viewHolder = recyclerView?.findViewHolderForAdapterPosition(currentPosition)
                        if (viewHolder is VideoPagerAdapter.VideoViewHolder) {
                            val videoCover = viewHolder.getVideoCover()
                            videoCover.visibility = android.view.View.VISIBLE
                            // 解绑 ExoPlayer，防止残影和黑屏
                            viewHolder.getPlayerView().player = null
                        }
                        onVideoPauseListener?.invoke(video, currentPosition)
                        Log.d(TAG, "暂停视频: ${video.title} at position: $currentPosition")
                    }
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "pauseCurrentVideo error: ${e.message}")
            e.printStackTrace()
        }
    }
    
    /**
     * 暂停当前播放的视频（供外部调用）
     */
    fun pause() {
        pauseCurrentVideo()
    }
    
    /**
     * 手动播放指定位置的视频
     */
    fun playVideoAtPosition(position: Int) {
        try {
            if (position >= 0) {
                currentPosition = position
                playCurrentVideo()
            }
        } catch (e: Exception) {
            Log.e(TAG, "playVideoAtPosition error: ${e.message}")
        }
    }
    
    fun release() {
        try {
            pauseCurrentVideo()
            exoPlayerManager?.release()
            recyclerView = null
            exoPlayerManager = null
            onVideoPlayListener = null
            onVideoPauseListener = null
            currentPosition = -1
            Log.d(TAG, "释放视频播放管理器")
        } catch (e: Exception) {
            Log.e(TAG, "释放视频播放管理器失败: ${e.message}")
        }
    }
    
    fun getCurrentPosition(): Int {
        return currentPosition
    }
} 